package gdut.edu.demo04;

import java.util.Arrays;

/**
 * @Description 归并排序
 * @Author JiaFu
 * @Date 2022/11/10 20:17
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = new int[]{2, 3, 1, 6, 8, 4, 2, 9, 0};
        mergeSort(arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));

    }

    public static void mergeSort(int[] arr,int low,int high){
        if (low < high){
            int middle = (low+high)/2;
            //处理左边
            mergeSort(arr,low,middle);
            //处理右边
            mergeSort(arr,middle+1,high);
            //归并
            merge(arr,low,middle,high);
        }
    }

    public static void merge(int[] arr, int low, int middle, int high) {//middle是分割线，左边数组包含middle
        //定义一个临时数组保存数据，左右两个数组都是有序的
        int[] tempArr = new int[high - low + 1];
        //记录左边数组遍历的下标
        int lowIndex = low;
        //记录右边数组遍历的下标
        int highIndex = middle+1;
        //记录遍历存放临时数据的数组的下标
        int tempIndex = 0;
        //遍历两个数组，取出较小的数据存放到临时数组
        while (lowIndex <= middle && highIndex <= high) {
            //如果左边数组的数据更小
            if (arr[lowIndex] <= arr[highIndex]) {
                //将数据存储到临时数组
                tempArr[tempIndex] = arr[lowIndex];
                //让下标后移一位
                lowIndex++;
            } else {
                tempArr[tempIndex] = arr[highIndex];
                highIndex++;
            }
            tempIndex++;
        }
        //处理多余的数据
        while (lowIndex <= middle) {
            tempArr[tempIndex] = arr[lowIndex];
            lowIndex++;
            tempIndex++;
        }
        while (highIndex <= high) {
            tempArr[tempIndex] = arr[highIndex];
            highIndex++;
            tempIndex++;
        }
        //把临时数组的数据放入原数组
        for (int k = 0; k < tempArr.length; k++) {
            arr[k + low] = tempArr[k];
        }
    }
}
